
package com.english.dao.hibernate;

import java.util.List;

import com.english.dao.hibernate.BaseDaoHibernate;
import com.english.model.Type;
import com.english.dao.TypeDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class TypeDaoHibernate extends BaseDaoHibernate implements TypeDao {

    /**
     * @see com.english.dao.TypeDao#getTypes(com.english.model.Type)
     */
    public List getTypes(final Type type) {
        //return getHibernateTemplate().find("from Type");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (type == null) {
            return getHibernateTemplate().find("from Type");
        } else {
            // filter on properties set in the type
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(type).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Type.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.english.dao.TypeDao#getType(Long id)
     */
    public Type getType(final Long id) {
        Type type = (Type) getHibernateTemplate().get(Type.class, id);
        if (type == null) {
            log.warn("uh oh, type with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Type.class, id);
        }

        return type;
    }

    /**
     * @see com.english.dao.TypeDao#saveType(Type type)
     */    
    public void saveType(final Type type) {
        getHibernateTemplate().saveOrUpdate(type);
    }

    /**
     * @see com.english.dao.TypeDao#removeType(Long id)
     */
    public void removeType(final Long id) {
        getHibernateTemplate().delete(getType(id));
    }
}
